﻿/**
 * 表格vxe-table自适应公共代码
 * 自适应类别：
 *     adaptSetting.type === 0(完全自适应 ) || 1(高度自适应) || 2(宽度自适应) || 3(自定义)
 * this.typeSetting  区别表格不同类型：
 *     horizontal              横表
 *     vertical                纵表
 * this.name 区别不同组件:
 *     page-table             表格
 *     page-table-crosstab    交叉表
 *     group-with-icon-list   分组带图标列表
 *     dimension-measure-table 维度度量表
 */
import validateAPI from '@/apis/validate-api';
import dfCssStyle from '@/components/page-table-panel-property/cssStyle-default.js';
import { fieldTypeOptions } from '@/components/panel-data/components/table-column-default-config';
import EventBus from '@/event-bus/EventBus.js';
import dataModel from '@/models/panel-config-data.js';
import { convertFormData, convertValue, dePermil, getDecimal, getXtagAggParams, numFormat } from '@/utils/util';
import { omitBy, uniqBy, cloneDeep } from 'lodash';
import { nextTick } from 'vue';
import nameDefault from './name-default';

const EXPORT_KEY = 'asyncExportTableDataKey';
export default {
  emits: ['xvue-download-exported-file'],
  data() {
    return {
      taskId: null,
      dfCssStyle,
      columnConfigList: [], // 列设置
    };
  },
  created() {
    this.handleSessionTaskId();
  },
  beforeUnmount() {
    if (this.taskId) {
      EventBus.$off(`xvue-download-exported-file-completed-${this.taskId}`);
    }
  },
  methods: {
    noDataMessage() {
      const { noDataPromptType, noDataPrompt } = this.config.config.property || {};
      if (noDataPromptType === 'customPrompt') {
        return noDataPrompt;
      }
      if (noDataPromptType === 'noPrompt') {
        return ' ';
      }
      return this.$demoi18n('message.noData');
    },
    updateColumnIdAndConfig(columnSetList) {
      // 列设置中相同列有多个时，取最后的配置
      const columnSetListUniq = uniqBy((cloneDeep(columnSetList) || []).reverse(), 'name').reverse();
      this.columnConfigList = columnSetListUniq;
    },
    headerStyle({ row = {}, column, columnIndex, rowIndex }) {
      const style = this.getCssStyle('headerStyle', this.style[this.componentStyle].header);
      this.setCommonStyle(style, 'titleStyle');
      const columnStyle = this.getColumnStyle(row, column);
      return { ...style, ...columnStyle };
    },
    cellStyle({ row, column, columnIndex, rowIndex }) {
      // 获取列的样式设置，列的样式设置只比阈值设置优先级低
      const columnStyle = this.getColumnStyle(row, column);
      const style = this.contentStyle;
      let { color, backgroundColor } = style;
      if (columnStyle) {
        color = columnStyle.color;
      }
      const contentExtraStyle = this.getCssStyle('contentExtraStyle');
      const { isStripeVisiable, stripeBgColor } = contentExtraStyle;

      // 设置斑马纹背景颜色
      const isStripeBgColorTransparent = stripeBgColor && stripeBgColor.length === 9 && stripeBgColor.lastIndexOf('00') === 7;
      if (isStripeVisiable && rowIndex % 2 === 1 && !isStripeBgColorTransparent) {
        backgroundColor = stripeBgColor;
      }
      const { isThreshold, threshold } = this.config.config.property;
      if (!isThreshold || threshold.length === 0) {
        return { ...this.contentStyle, backgroundColor, ...columnStyle };
      }

      const isVeritalWithoutEntireRow =
      this.typeSetting === 'vertical' && !this.thresholdRows.find(_row => _row.index === rowIndex);
      const isHorizWithoutEntireCol =
      this.typeSetting === 'horizontal' && !this.thresholdColumns.find(col => col.index === columnIndex);
      if (isVeritalWithoutEntireRow || isHorizWithoutEntireCol) {
        // 单元格渲染
        threshold.forEach(threItem => {
          if (column.property === threItem.field || row.col0 === threItem.field) {
            let value = row[column.property];
            if (this.getCurFieldObj(threItem.fieldType).type === 'num' && value) {
              value = Number(value.toString().replace(/,/g, ''));
            }
            const isNumScope =
              this.getCurFieldObj(threItem.fieldType).type === 'num' &&
              Number(value) >= Number(threItem.min) &&
              Number(value) < Number(threItem.max);
            const isTextScope = value !== '' && value === threItem.text;

            if (isNumScope || isTextScope) {
              color = threItem.color;
            }
          }
        });
      } else if (this.typeSetting === 'vertical') {
        // 纵表行渲染
        this.thresholdRows.forEach(_row => {
          if (_row.index === rowIndex) {
            color = _row.color;
          }
        });
      } else {
        // 横表列渲染
        this.thresholdColumns.forEach(_column => {
          if (_column.index === columnIndex) {
            color = _column.color;
          }
        });
      }
      return { ...this.contentStyle, backgroundColor, ...columnStyle, color };
    },
    handleSessionTaskId() {
      const taskId = sessionStorage.getItem(`${EXPORT_KEY}_${this.widgetInstanceId}`);

      if (!taskId || !window.xVueWeb.app?.config?.globalProperties?.$xvueDownloadedFileByTaskIds) {
        this.taskId = null;
        return;
      }

      const isTaskIdExist = window.xVueWeb.app?.config?.globalProperties?.$xvueDownloadedFileByTaskIds.find(item => item.taskId === taskId);
      if (!isTaskIdExist || isTaskIdExist.completed) {
        this.taskId = null;
        return;
      }
      this.taskId = isTaskIdExist.taskId;
      EventBus.$on(`xvue-download-exported-file-completed-${this.taskId}`, this.clearTaskId);
    },
    clearTaskId() {
      EventBus.$off(`xvue-download-exported-file-completed-${this.taskId}`);
      sessionStorage.removeItem(`${EXPORT_KEY}_${this.widgetInstanceId}`);
      this.taskId = null;
    },
    handleAsyncExportTableData(res) {
      const { data: componentData } = this.config.config;
      const { dataSourceType } = componentData;
      const { data: taskId, msg } = res || {};
      if (!taskId) {
        this.$message.error(msg || this.$demoi18n('word.exportFailed'));
        return;
      } else {
        this.$message(this.$demoi18n('word.exportTip'));
      }

      // 存入taskId
      this.taskId = taskId;
      sessionStorage.setItem(`${EXPORT_KEY}_${this.widgetInstanceId}`, taskId);

      // 任务ID发给xvue
      EventBus.$emit('xvue-download-exported-file', { taskId, type: dataSourceType });

      // 绑定该id等待接收下载完成事件
      EventBus.$on(`xvue-download-exported-file-completed-${taskId}`, this.clearTaskId);
    },
    setAdjustWH() {
      this.styleInit();
      const adaptSetting = this.getAdaptSetting();
      if (!adaptSetting) {
        return;
      }
      this.contentReset();
      this.setTableProp();
      setTimeout(() => {
        this.adjustContent();
      }, 100);
    },
    setTableProp() {
      if (this.tableData.length === 0) {
        return;
      }
      const curComp = document.getElementById(`chartMain${this.chartId}`);
      const tableBody = curComp.getElementsByClassName('vxe-table--body')[0];
      const adaptSetting = this.getAdaptSetting();
      this.setTableBodyProp(tableBody, adaptSetting);

      // 表格横表、交叉表左侧列table-body自适应单独设置
      if (this.typeSetting === 'horizontal' || this.hasName('leftTableBody')) {
        const fixedTable = curComp.getElementsByClassName('vxe-table--fixed-left-wrapper')[0];
        if (fixedTable) {
          const fixedTableBody = fixedTable.getElementsByClassName('vxe-table--body')[0];
          this.setTableBodyProp(fixedTableBody, adaptSetting);
        }
      }
    },
    setTableBodyProp(el, adaptSetting) {
      if (adaptSetting.type === '0' || adaptSetting.type === '1') {
        if (this.tableData.length < this.tablePage.pageSize && this.tablePage.currentPage > 1) {
          el.style.height = 'auto';
        } else {
          el.style.height = '100%';
        }
      } else {
        el.style.height = 'auto';
      }
    },

    // 交叉表首列位移计算
    _adjustContentFirstOffset() {
      if (!this.hasName('firstOffset')) {
        return;
      }
      const curComp = document.getElementById(`chartMain${this.chartId}`);
      const tableMain = curComp.getElementsByClassName('vxe-table--main-wrapper')[0];
      const tableMainFooter = tableMain.getElementsByClassName('vxe-table--footer-wrapper')[0];
      const tableFixedLeft = curComp.getElementsByClassName('vxe-table--fixed-left-wrapper')[0];
      if (tableFixedLeft) {
        const tableHeaderWrapper = tableFixedLeft.getElementsByClassName('vxe-table--header-wrapper')[0];
        const tableBodyWrapper = tableFixedLeft.getElementsByClassName('vxe-table--body-wrapper')[0];
        const tableFooterWrapper = tableFixedLeft.getElementsByClassName('vxe-table--footer-wrapper')[0];
        if (tableBodyWrapper) {
          tableBodyWrapper.style.top = `${tableHeaderWrapper.clientHeight}px`;
          if (tableFooterWrapper) {
            tableBodyWrapper.style.height = `${tableFixedLeft.clientHeight -
                tableHeaderWrapper.clientHeight -
                tableFooterWrapper.clientHeight}px`;
          } else {
            tableBodyWrapper.style.height = `${tableFixedLeft.clientHeight - tableHeaderWrapper.clientHeight}px`;
          }
        }
        if (tableFooterWrapper) {
          tableFooterWrapper.style.top = `${tableMain.clientHeight - tableMainFooter.clientHeight}px`;
        }
      }
    },

    adjustContent() {
      if (this.tableData.length === 0) {
        return;
      }
      const adaptSetting = this.getAdaptSetting();
      const curComp = document.getElementById(`chartMain${this.chartId}`);
      const tableBody = curComp.getElementsByClassName('vxe-table--body')[0];
      const tableBodyWrap = curComp.getElementsByClassName('vxe-table--body-wrapper')[0];
      if (adaptSetting.type === '0' || adaptSetting.type === '1' || adaptSetting.type === '2') {
        const tableBodyRow = tableBody.getElementsByClassName('vxe-body--row')[0];
        const contentGap = tableBody.offsetHeight - tableBodyWrap.offsetHeight;
        if (contentGap >= 0 && contentGap / tableBodyRow.clientHeight < 0.25) {
          tableBodyWrap.style['overflow-y'] = 'hidden';
        } else {
          tableBodyWrap.style['overflow-y'] = 'auto';
        }
        if (adaptSetting.type === '2') {
          if (contentGap > tableBodyRow.clientHeight / 8) {
            tableBodyWrap.style['overflow-y'] = 'auto';
          } else {
            tableBodyWrap.style['overflow-y'] = 'hidden';
          }
        }
      }
      if (adaptSetting.type === '0' || adaptSetting.type === '2') {
        const tableBodyColumn = tableBody.getElementsByClassName('vxe-body--column')[0];
        const contentGap = tableBody.offsetWidth - tableBodyWrap.offsetWidth;
        if (contentGap >= 0 && contentGap / tableBodyColumn.clientWidth < 0.25) {
          tableBodyWrap.style['overflow-x'] = 'hidden';
        } else {
          tableBodyWrap.style['overflow-x'] = 'auto';
        }
      }

      this._adjustContentFirstOffset(); // 为降低圈复杂度做拆分
    },
    styleInit() {
      if (!this.config) {
        return;
      }
      this.contentStyleFn();
      this.footerStyleFn();

      const curComp = document.getElementById(`chartMain${this.chartId}`);
      const vxeTable = curComp.getElementsByClassName('vxe-table')[0];
      if (this.tablePage.enabled && !this.isNoData) {
        const gridPageWrap = curComp.getElementsByClassName('vxe-grid--pager-wrapper')[0];
        const pageWrap = curComp.getElementsByClassName('vxe-pager--wrapper')[0];
        const pageWrapInput = pageWrap.getElementsByClassName('vxe-input--inner')[0];
        const pageWrapGoto = pageWrap.getElementsByClassName('vxe-pager--goto')[0];
        vxeTable.style.height = `calc(99.9% - ${gridPageWrap.clientHeight}px)`;

        // 底部页码的字体
        pageWrap.style.fontSize = this.contentStyle.fontSize;
        if (pageWrapInput) {
          pageWrapInput.style.fontSize = this.contentStyle.fontSize;
        }
        if (pageWrapGoto) {
          pageWrapGoto.style.fontSize = this.contentStyle.fontSize;
        }
      } else {
        vxeTable.style.height = '99.9%';
      }
      if (this.$refs.basicVxeTable) {
        this.$refs.basicVxeTable.reloadColumn(this.tableColumn);
      }
    },
    getColumnStyle(row, column) {
      let currentColumnSetting = {};
      if (this.typeSetting === 'horizontal') {
        currentColumnSetting = this.columnConfigList.find(item=>item.name === row.col0);
      } else {
        currentColumnSetting = this.columnConfigList.find(item=>item.name === column.field);
      }
      const { color, backgroundColor, fontSize, fontWeight } = currentColumnSetting || {};
      const settingStyle = omitBy(
        { color, backgroundColor, fontSize: fontSize ? `${fontSize}px` : undefined, fontWeight },
        value=>(!value && value !== 0),
      );
      return currentColumnSetting ? settingStyle : {};
    },
    headerStyleFn() {
      const style = this.getCssStyle('headerStyle', this.style[this.componentStyle].header);
      this.setCommonStyle(style, 'titleStyle');
      this.headerStyle = style;
    },
    contentStyleFn() {
      const style = this.getCssStyle('contentStyle', this.style[this.componentStyle].cell);
      this.setCommonStyle(style, 'lineStyle');
      this.contentStyle = style;
    },
    footerStyleFn() {
      const style = this.getCssStyle('footerStyle', this.style[this.componentStyle].footer);
      this.setCommonStyle(style, 'footerStyle');
      this.footerStyle = style;
    },

    // 交叉表首列样式修改
    _setCommonStyleFirstCol(borderColor) {
      if (!this.hasName('firstColStyle')) {
        return;
      }

      const adaptSetting = this.getAdaptSetting();
      const curComp = document.getElementById(`chartMain${this.chartId}`);
      const fixedColumn = curComp.getElementsByClassName('vxe-table--fixed-left-wrapper')[0];
      if (!fixedColumn) {
        return;
      }
      const fixedHeader = fixedColumn.getElementsByClassName('vxe-table--header-border-line')[0];
      const fixedHeaderWrapper = fixedColumn.getElementsByClassName('vxe-table--header')[0];
      const fixedHeaderCloumn = fixedHeaderWrapper.getElementsByClassName('vxe-header--column')[0];
      const fixedFooterWrapper = fixedColumn.getElementsByClassName('vxe-table--footer')[0];

      // 合计上方白线
      const fixedFooter = fixedColumn.getElementsByClassName('vxe-table--footer-wrapper')[0];
      if (this.borderType === 'full') {
        if (adaptSetting.type === '0' || adaptSetting.type === '1') {
          fixedHeaderCloumn.style.borderBottom = 'none';
        } else {
          fixedHeaderCloumn.style.borderBottom = `1px solid ${borderColor}`;
        }
        fixedColumn.style.borderRight = 'none';
      } else {
        fixedColumn.style.borderRight = 'none';
        fixedHeaderCloumn.style.borderBottom = 'none';
      }
      fixedHeader.style.borderBottom = `1px solid ${borderColor}`;
      if (fixedFooter) {
        fixedFooter.style.borderTop = `1px solid ${borderColor}`;
      }
      if (fixedFooterWrapper) {
        const fixedFooterCloumn = fixedFooterWrapper.getElementsByClassName('vxe-footer--column')[0];
        if (fixedFooterCloumn) {
          fixedFooterCloumn.style.borderBottom = `1px solid ${borderColor}`;
        }
      }
    },

    _setHeight(obj) {
      const adaptSetting = this.getAdaptSetting();
      const curComp = document.getElementById(`chartMain${this.chartId}`);
      const tableContentWrapper = curComp.getElementsByClassName('tableContentBox-main')[0];
      const tableFooter = curComp.getElementsByClassName('vxe-table--footer')[0];
      const tableHeader = curComp.getElementsByClassName('vxe-table--header-wrapper')[0];
      const pageWrap = curComp.getElementsByClassName('vxe-grid--pager-wrapper')[0];

      // 只有在有数据时才去设置表格行高
      if (this.tableData.length > 0) {
        let height = tableContentWrapper.offsetHeight;
        let _length = 0;

        // enabled  分页开启
        if (this.tablePage.enabled) {
          height = tableContentWrapper.offsetHeight - pageWrap.offsetHeight;

          // 数据总数tableData小于tablePage.pageSize时，_length需赋值总数tableData.length
          _length = this.tableData.length <= this.tablePage.pageSize ? this.tableData.length : this.tablePage.pageSize;

          // 横表、交叉表tableData含有的数据按照tablePage.pageSize计算，所有这里应赋值tableData.length
          if (this.typeSetting === 'horizontal' || this.hasName('tableDataLength')) {
            _length = this.tableData.length;
          }
        } else {
          _length = (this.tableData.length === 0) ? this.tablePage.pageSize : this.tableData.length;
        }

        if (tableFooter) {
          _length += 1;
        }
        if (tableHeader) {
          _length += 1;
        }
        if (adaptSetting.type === '0' || adaptSetting.type === '1') {
          const unitHeight = height / _length;
          obj.height = `${unitHeight}px`;
        }
        if (adaptSetting.type === '2' || adaptSetting.type === '3') {
          const { lineGap } = this.getCssStyle(adaptSetting);
          obj.height = lineGap;
        }
      }
    },

    setCommonStyle(obj, key) {
      const dfStyle = { aligns: 'left' };
      const { titleStyle = dfStyle, lineStyle = dfStyle, table } = this.config.config.property;
      const styleObj = {
        lineStyle,
        titleStyle,
        footerStyle: lineStyle,
      };

      this._setHeight(obj);
      obj.lineHeight = 1.2;
      obj.verticalAlign = obj.vertical;
      obj.textAlign = obj.horizontal || styleObj[key].aligns;

      // 边框颜色
      const borderColor = (table && table.borderColor) || this.style[this.componentStyle].borderColor;
      if (this.borderType === 'default') {
        obj.backgroundImage = `linear-gradient(${borderColor},${borderColor})`;
      } else if (this.borderType === 'full' || this.borderType === 'inner') {
        obj.backgroundImage = `linear-gradient(${borderColor},${borderColor}),` +
          `linear-gradient(${borderColor},${borderColor})`;
      } else {
        obj.backgroundImage = 'none';
      }

      this._setCommonStyleFirstCol(borderColor); // 为降低圈复杂度做拆分
    },

    contentReset() {
      const curComp = document.getElementById(`chartMain${this.chartId}`);
      const adaptSetting = this.getAdaptSetting();
      const tableBodyWrapper = curComp.getElementsByClassName('vxe-table--body-wrapper');

      const cellDom = curComp.getElementsByClassName('vxe-cell');
      if (cellDom && cellDom.length > 0) {
        for (let i = 0; i < cellDom.length; i++) {
          if (adaptSetting.type === '0' || adaptSetting.type === '1') {
            cellDom[i].style.height = '';
          }
          if (adaptSetting.type === '1' || adaptSetting.type === '3') {
            cellDom[i].style.width = '';
          }
        }
      }
      for (let k = 0; k < tableBodyWrapper.length; k++) {
        const allRowClass = tableBodyWrapper[k].getElementsByClassName('vxe-body--row');
        for (let j = 0; j < allRowClass.length; j++) {
          allRowClass[j].style.height = '';
        }
      }
    },
    updateStyle() {
      const { table } = this.config.config.property;
      this.borderType = (table && table.border) || 'full';
      const backgroundColor = (table && table.backgroundColor) || this.style[this.componentStyle].box.backgroundColor;

      // 边框颜色、表格背景等无法通过配置项解决的，通过原生js修改
      nextTick(() => {
        const curComp = document.getElementById(`chartMain${this.chartId}`);

        // 表格背景
        const bodyWraper = curComp.getElementsByClassName('body--wrapper');
        for (let i = 0; i < bodyWraper.length; i++) {
          bodyWraper[i].style.backgroundColor = backgroundColor;
        }

        // 边框颜色
        const borderColor = (table && table.borderColor) || this.style[this.componentStyle].borderColor;
        const headerBorder = curComp.getElementsByClassName('vxe-table--header-border-line');
        const outerBorder = curComp.getElementsByClassName('vxe-table--border-line');
        const footerBorder = curComp.getElementsByClassName('vxe-table--footer-wrapper');
        if (headerBorder.length !== 0) {
          headerBorder[0].style.borderColor = borderColor;
        }
        if (footerBorder.length !== 0) {
          footerBorder[0].style.borderTop = `1px solid ${borderColor}`;
          if (this.borderType === 'none') {
            footerBorder[0].style.border = 'none';
          }
        }
        outerBorder[0].style.borderColor = borderColor;
      });
    },
    handlePagerAdjust(w) {
      if (w >= 900) {
        this.tablePage.layouts = [
          'Total',
          'Sizes',
          'PrevJump',
          'PrevPage',
          'JumpNumber',
          'NextPage',
          'NextJump',
          'FullJump',
        ];
      } else if (w >= 800) {
        this.tablePage.layouts = ['Total', 'Sizes', 'PrevPage', 'JumpNumber', 'NextPage', 'FullJump'];
      } else if (w >= 550) {
        this.tablePage.layouts = ['Total', 'Sizes', 'PrevPage', 'NextPage', 'FullJump'];
      } else if (w >= 400) {
        this.tablePage.layouts = ['Total', 'PrevPage', 'NextPage', 'FullJump'];
      } else {
        this.tablePage.layouts = ['Total', 'PrevPage', 'NextPage'];
      }
    },
    updateFixedColumnStyle() {
      setTimeout(() => {
        const { table } = this.config.config.property;
        const backgroundColor = (table && table.backgroundColor) || this.style[this.componentStyle].box.backgroundColor;
        const curComp = document.getElementById(`chartMain${this.chartId}`);

        // 表格背景
        const fixedColumn = curComp.getElementsByClassName('fixed-left--wrapper');
        if (fixedColumn.length === 0) {
          return;
        }
        for (let i = 0; i < fixedColumn.length; i++) {
          if (fixedColumn[i].style.backgroundColor !== backgroundColor) {
            fixedColumn[i].style.backgroundColor = backgroundColor;
          }
          fixedColumn[i].style.overflow = 'hidden';
        }
      }, 100);
    },

    _getFooterSumByName(sum, column, columnIndex) {
      let _sum = sum;
      switch (this.name) {
        case 'page-table': {
          const { tableData } = this.config.config.data;
          const curCell = tableData.find(col => col.field === column.property);
          _sum =
            curCell && curCell.fieldType === 'number' ?
              this.handleThousandSeparator(curCell, getDecimal(_sum, this.totalDecimal)) :
              '/';
          break;
        }
        case 'group-with-icon-list':
          _sum = numFormat(getDecimal(_sum, this.totalDecimal), true);
          break;
        case 'dimension-measure-table': {
          let { tableData } = this.config.config.data;
          tableData = tableData.filter(item => item.fieldType);
          const curCell = tableData.find(col => col.field === column.title);
          const { tableTile } = this;
          if (columnIndex < tableTile.length) {
            _sum =
              curCell && curCell.fieldType === 'number' ?
                this.handleThousandSeparator(curCell, getDecimal(_sum, this.totalDecimal)) :
                '/';
          } else {
            _sum = numFormat(getDecimal(_sum, this.totalDecimal), this.isThousandSeparator);
          }
          break;
        }
        default:
          _sum = numFormat(getDecimal(_sum, this.totalDecimal), this.isThousandSeparator);
          break;
      }
      return _sum;
    },

    // 合计
    footerMethods(columns, data) {
      const arr = columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return this.$demoi18n('view.table.sums');
        }
        const values = data.map(item => {
          if (item[column.property] === null || item[column.property] === undefined) {
            return Number(item[column.property]);
          }
          return Number(item[column.property].toString().replace(/,/g, ''));
        });
        let sum = [];
        if (values.some(value => !isNaN(value))) {
          sum = values.reduce((prev, curr) => {
            let _prev = prev;
            let _curr = curr;
            const value = Number(curr);
            if (!isNaN(value)) {
              _prev = (Math.pow(10, this.totalDecimal) * _prev) / Math.pow(10, this.totalDecimal);
              _curr = Math.pow(10, this.totalDecimal) * _curr;
              return _prev + _curr;
            } else {
              return prev;
            }
          }, 0);
          sum = this._getFooterSumByName(sum, column, columnIndex);
        } else {
          sum = '/';
        }
        return sum;
      });
      return [arr];
    },

    // 不同表格区分
    hasName(key) {
      const { name } = this;
      let conf = nameDefault[name] || {};
      if (this.nameDefault) {
        conf = { ...conf, ...nameDefault };
      }
      return conf[key];
    },

    _btnStyle(val) {
      const { exportBtnDist, exportBtnSize, checkBtnDist, checkBtnSize, cssStyle } = this.config.config.property;
      const { exportBtnStyle, checkBtnStyle } = cssStyle || {};

      const btnDist = val === 'export' ? exportBtnDist : checkBtnDist;
      const btnSize = val === 'export' ? exportBtnSize : checkBtnSize;
      const btnStyle = val === 'export' ? exportBtnStyle : checkBtnStyle;
      const style = {};

      if (btnDist) {
        style.top = btnDist[0].value;
        style.bottom = btnDist[1].value;
        style.left = btnDist[2].value;
        style.right = btnDist[3].value;
      }
      if (btnSize) {
        style.width = btnSize[0].size.value;
        style.height = btnSize[1].size.value;
        style.widthUnit = btnSize[0].unit;
        style.heightUnit = btnSize[1].unit;
      }
      if (this.checkBtnDisabled && val === 'check') {
        style.backgroundColor = this.getValByCompStl('#a0cfff', '#064559', '#3e3e3e');
        style.borderColor = `${this.getValByCompStl('#a0cfff', '#187e91', '#676767')}!important`;
      } else if (cssStyle && btnStyle) {
        const bColor = `${btnStyle.backgroundColor}!important`;
        style.borderColor = bColor;
        style.backgroundColor = bColor;
        style.color = btnStyle.color;
        style.fontSize = btnStyle.fontSize;
        style.fontWeight = btnStyle.fontWeight;
        style.fontFamily = btnStyle.cofontFamilylor;
      } else {
        if (val === 'export') {
          const bColor = `${this.getValByCompStl('#409EFF', '#187e91', '#232323')}!important`;
          style.borderColor = bColor;
          style.backgroundColor = bColor;
        }
      }
      return style;
    },

    // 全量导出与多选导出
    btnStyle(val) {
      const style = this._btnStyle(val);

      const top = style.top || 0;
      const bottom = style.bottom || 10;
      const left = style.left || 20;
      const right = style.right || 0;
      const width = style.width || 80;
      const height = style.height || 28;
      const widthUnit = style.widthUnit || 'px';
      const heightUnit = style.heightUnit || 'px';
      const { backgroundColor } = style;
      const color = style.color || '#fff';
      const fontFamily = style.fontFamily || 'unset';
      const fontSize = style.fontSize || 12;
      const fontWeight = style.fontWeight || 'normal';
      const { borderColor } = style;
      return {
        margin: `${top}px ${right}px ${bottom}px ${left}px`,
        width: `${width}${widthUnit}`,
        height: `${height}${heightUnit}`,
        backgroundColor,
        color: `${color}!important`,
        fontSize: `${fontSize}px`,
        fontFamily,
        fontWeight,
        borderColor,
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        whiteSpace: 'nowrap',
      };
    },
    handleThousandSeparator(cell, value) {
      const isThousandSeparator = this.isThousandSeparator && cell.fieldType !== 'string' && cell.fieldType !== 'status';
      const res = numFormat(value, isThousandSeparator) ?? '-';
      return res;
    },

    /*
     * 自定义样式渲染逻辑
     * 获取当前单元格配置项
     */
    getCurCell(row, column) {
      let curCell = {};
      let { tableData } = this.config.config.data;
      if (this.curComp) {
        tableData = this.config.config.data.table.tableData;
      }

      curCell = tableData.find(item => item.field === column.title);

      return curCell || {};
    },

    // 自定义样式类别确定
    customStyle(row, column) {
      let renderStyle;
      const curCell = this.getCurCell(row, column);
      switch (curCell.fieldType) {
        case 'percentage':
          renderStyle = curCell.style.perStyle;
          break;
        case 'status':
          renderStyle = curCell.style.statusStyle;
          break;
        default:
          break;
      }
      return renderStyle;
    },

    // 百分比值计算
    percentageValue(row, column) {
      let value = row[column.property];
      if (this.isThousandSeparator) {
        value = dePermil(value);
      }
      value = Number(value);
      if (isNaN(value)) {
        return 0;
      }
      const curCell = this.getCurCell(row, column);
      const { style } = curCell;
      const { basis, targetNum, percentDecimalCount } = style;
      if (basis === 'maxTagetNum') {
        value = ((value / targetNum) * 100).toFixed(percentDecimalCount);
      }
      return value;
    },
    percentageTrueValue(row, column) {
      const value = this.percentageValue(row, column);
      return Number(value);
    },

    // 百分比颜色
    percentageColor(row, column) {
      const curCell = this.getCurCell(row, column);
      const { style } = curCell;
      const { color } = style;
      return color;
    },
    percentageStyle(row, column) {
      const curCell = this.getCurCell(row, column);
      const { style } = curCell;
      const { valueWidth } = style;
      return {
        width: `calc(100% - ${convertValue(valueWidth)}px)`,
        display: 'inline-block',
        marginRight: `${convertValue(10)}px`,
      };
    },

    // 状态图标
    statusIcon(row, column) {
      const curCell = this.getCurCell(row, column);

      const { style } = curCell;
      const { statusTable } = style;
      const curIcon = statusTable.find(item => item.statusField.toString() === row[column.property]);
      return curIcon && curIcon.icon;
    },

    // 跳转样式
    jumpCellStyle(row, column) {
      const data = this.getCurCell(row, column);

      const jumpUrls = this.getJumpUrls(data);
      if (jumpUrls.length === 0) {
        return '';
      }
      return 'jump-cell';
    },
    getJumpUrls(data) {
      const { advancedLinkage, jumpParams } = data;
      let jumpUrls = [];
      if (advancedLinkage) {
        advancedLinkage.linkageDatas.forEach(n => {
          if (n.hasLink) {
            jumpUrls.push(n.jumpUrl);
          }
        });
      } else {
        const jumpUrl = jumpParams && jumpParams.jumpUrl;
        if (jumpUrl) {
          jumpUrls = [jumpUrl];
        }
      }
      return jumpUrls;
    },
    sendAdvLinkage(column, rowIndex, columnIndex) {
      let srcValues = {};
      let { tableData } = this.config.config.data;
      const extKey = column.property;
      if (this.curComp) {
        tableData = this.config.config.data.table.tableData;
      }
      srcValues = this.selectRow;
      const { advancedLinkage } = tableData[columnIndex];
      if (this.hasName('sendAdvLinkageDimension')) {
        this.sendAdvancedLinkagge(srcValues, advancedLinkage, extKey);
      } else {
        this.sendAdvancedLinkagge(srcValues, advancedLinkage);
      }
    },
    exportDataAll() {
      const { data: componentData } = this.config.config;
      const { dataSourceType, tableData, dataPackage, dataTable } = componentData;

      // xMiner导出是原逻辑
      if (dataSourceType === 'xMiner') {
        const { params } = this;
        if (params.params.length > 0) {
          params.params.forEach(param => {
            if (param.wid) {
              delete param.wid;
            }
          });
        }

        // 表格异步导出
        const exportDataParams = JSON.parse(JSON.stringify(params));
        delete exportDataParams.propertyMapping;
        delete exportDataParams.pageSize;
        exportDataParams.pageIndex = 1;

        // 删除isCommon\isAdvanced否则接口参数不通过
        if (exportDataParams.params && Array.isArray(exportDataParams.params)) {
          exportDataParams.params.forEach(param => {
            delete param.isCommon;
            delete param.isAdvanced;
          });
        }
        dataModel.asyncExportTableData(exportDataParams).then(this.handleAsyncExportTableData);
      }

      // 新增适配xTag导出逻辑
      if (dataSourceType === 'xTag') {
        if (!dataPackage) {
          return;
        }
        const params = {
          conditions: [],
          propertyMapping: convertFormData(tableData),
          sqlParams: [],
        };
        getXtagAggParams(params, tableData);
        const method = 'exportAllValueByTableNameAndFields';
        dataModel[method](dataTable, params, dataPackage).then(this.handleAsyncExportTableData);
      }
    },
    exportDataChecked() {
      const data = this.$refs.basicVxeTable.getCheckboxRecords(true);

      // DDE注入校验
      const params = {
        header: this.hasHeader ? this.tableColumn.map(column => column.title) : [], // 表头数据处理
        list: data,
      };
      validateAPI
        .validateDDEText(params)
        .then(res => {
          const { data: _data } = res.data;
          const exptHeader = _data.header;
          const exptData = _data.list;

          // 表头数据拼接
          if (this.hasHeader) {
            const hRow = {};
            params.header.forEach((key, index) => {
              hRow[key] = exptHeader[index];
            });
            exptData.unshift(hRow);
          }
          this.$refs.basicVxeTable.exportData({
            isFooter: false,
            isHeader: false,
            data: exptData,
            original: true,

            // 筛选列不导出
            columnFilterMethod({ column }) {
              return Boolean(column.property);
            },
          });
        })
        .catch(err => {
          this.$message.error(this.$demoi18n('view.exportFail'));
        });
    },
    handleThreshold(columnAssist, tableData) {
      const { hasColumnHeader, isThreshold, threshold } = this.config.config.property;
      this.thresholdRows = [];
      if (!isThreshold) {
        return;
      }
      if (this.typeSetting === 'vertical') {
        // 判断纵表阈值列
        this.handleVerticalThreshold(threshold, columnAssist, tableData);
      } else {
        // 判断横表阈值列
        this.handleHorizontalThreshold(threshold, columnAssist, tableData, hasColumnHeader);
      }
    },
    handleVerticalThreshold(threshold, columnAssist, tableData) {
      const thresholdRows = [];
      threshold.forEach(threItem => {
        columnAssist.forEach(column => {
          if (column.field === threItem.field) {
            for (let i = 0; i < tableData.length; i++) {
              const value = tableData[i][column.field];
              const isNumScope =
                  this.getCurFieldObj(threItem.fieldType).type === 'num' &&
                  Number(value) >= Number(threItem.min) &&
                  Number(value) < Number(threItem.max);
              const isTextScope = value !== '' && value === threItem.text;
              let { isEntireRow } = threItem;
              if (isEntireRow === undefined) {
                isEntireRow = true;
              }
              if (isEntireRow && (isNumScope || isTextScope)) {
                const rowIndex = i;
                thresholdRows.push({ index: rowIndex, color: threItem.color });
              }
            }
          }
        });
      });
      this.thresholdRows = thresholdRows;
    },
    handleHorizontalThreshold(threshold, columnAssist, tableData, hasColumnHeader) {
      this.thresholdColumns = [];
      const thresholdColumns = [];
      threshold.forEach(threItem => {
        columnAssist.forEach(data => {
          if (data.col0 === threItem.field) {
            for (let i = 0; i < tableData.length + 1; i++) {
              let value = data[`col${i}`];
              if (this.getCurFieldObj(threItem.fieldType).type === 'num' && value) {
                value = Number(value.toString().replace(/,/g, ''));
              }
              const isNumScope =
                  this.getCurFieldObj(threItem.fieldType).type === 'num' &&
                  Number(value) >= Number(threItem.min) &&
                  Number(value) < Number(threItem.max);
              const isTextScope = value !== '' && value === threItem.text;
              let { isEntireRow } = threItem;
              if (isEntireRow === undefined) {
                isEntireRow = true;
              }
              if (isEntireRow && (isNumScope || isTextScope)) {
                let columnIndex = i;
                if (this.tableCheckBox) {
                  columnIndex++;
                }
                if (!hasColumnHeader) {
                  columnIndex--;
                }
                thresholdColumns.push({ index: columnIndex, color: threItem.color });
              }
            }
          }
        });
      });
      this.thresholdColumns = thresholdColumns;
    },
    getCurFieldObj(fieldType) {
      const obj = fieldTypeOptions.find(option => option.value === fieldType);
      return obj || {};
    },
  },
};
